
// 下单参数
/** 
 *  data.amount
    data.gid
    data.wtype
    data.chose_team 
*/

var ws = null;
var username = null;
var password = null;
var eventsMap = new Map();
var gid = false;

function loadScript(url) {
    var scriptElement = document.createElement('script');
    scriptElement.setAttribute('type', 'text/javascript');
    scriptElement.setAttribute('src', url);
    document.head.appendChild(scriptElement);
}

function init() {
    if (window.location.href == "about:blank") return
    // if (!window.location.href.startsWith("https://www") && !window.location.href.startsWith("https://m645")) return
    if (!gid) gid = Math.random()
    console.info("-----------------------------")
    console.info("<<<皇冠客户端准备就绪>>>")
    console.info("-----------------------------")
    try {
        loadJquery().then(conServer).then(login)
    } catch (e) {
        console.info(e.message)
    }
}

async function analysisPage() {
    // 判断当前网页是否被阻塞
    // 判断是否进入主页面  alert_show
    $("#C_no_btn").click()
    // 出现网络问题，点击确认按钮  
    $("#C_ok_btn_system").click()
    // 退出重登
    $("#kick_ok_btn").click()
    setTimeout(() => {
        analysisPage()
    }, 8000);
}

function login() {
    return new Promise((resolve, reject) => {
        function handler() {
            if (top.userData && top.userData.passwd_safe) {
                resolve(true)
            } else {
                let usr = document.getElementById("usr");
                let pwd = document.getElementById("pwd");
                // 如果不存在登录信息则一直等待到登录信息的出现
                if (usr && pwd && username && password) {
                    usr.value = username
                    pwd.value = password
                    document.getElementById("btn_login").click()
                } else {
                    setTimeout(() => {
                        handler()
                    }, 3000);
                }
            }
        }
        handler()
    })

}

function loadJquery() {
    return new Promise((resolve, reject) => {
        function load() {
            loadScript(`https://code.jquery.com/jquery-1.12.4.min.js`);
            setTimeout(() => {
                $ = jQuery;
                if (typeof $ == "function") {
                    analysisPage()
                    resolve(true)
                } else {
                    load()
                }
            }, 3000);
        }
        load()
    });
}

function conServer() {
    console.log("HG插件正在连接服务器>>>>>")
    let username = top.userData && top.userData.passwd_safe
    if (username) {
        ws = new WebSocket(`ws://127.0.0.1:8100/order?username=${username}`);
        ws.onopen = function () {
            console.log("本地代理服务器连接成功")
        }
        ws.onmessage = function (e) {
            console.info(e.data)
            let obj = JSON.parse(e.data)
            let event = eventsMap.get(obj.action)
            if (event) {
                event(obj.result)
            }
        }
        ws.onclose = function (e) {
            console.log("本地代理服务器连接失败 ");
            setTimeout(() => {
                conServer(true)
            }, 5000);
        }
        ws.onerror = function (e) {
        }
    } else {
        setTimeout(() => {
            conServer()
        }, 3000);
    }
}

function user(result) {
    username = result.username;
    password = result.password;
}


async function odds(data) {
    let host = location.host;
    let response = await fetch(`${location.protocol}//${host}/transform.php?ver=${top.ver}`, {
        "credentials": "include",
        "headers": {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0",
            "Accept": "*/*",
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Content-type": "application/x-www-form-urlencoded",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "Pragma": "no-cache",
            "Cache-Control": "no-cache",
            "Cookie": document.cookie
        },
        "referrer": `${location.protocol}//${host}/`,
        "body": `p=FT_order_view&${top.param}&odd_f_type=${top.userData.odd_f_type}&gid=${data.gid}&gtype=FT&wtype=${data.wtype}&chose_team=${data.chose_team}`,
        "method": "POST",
        "mode": "cors"
    });
    let gameData = await response.text();
    let preOrderResp = xml2json(gameData);
    console.info("查询赔率：" + JSON.stringify(preOrderResp))
    return preOrderResp
}

async function order(data, isTry) {
    try {
        let host = location.host;
        let preOrderResp = await odds(data)
        let ioratio = preOrderResp.serverresponse.ioratio;
        let con = preOrderResp.serverresponse.con;
        let ratio = preOrderResp.serverresponse.ratio;
        let timestamp2 = preOrderResp.serverresponse.ts;
        // rtype :  半场客: HREC
        // rtype :  半场主: HREH
        //          p=FT_bet&uid=oy81jjhm32831063l82507b0&ver=2024-03-28-newVer_4&langx=zh-cn&odd_f_type=H&golds=100&gid=6860667&gtype=FT&wtype=ROU&rtype=ROUC&chose_team=C&ioratio=0.78&con=2&ratio=50&autoOdd=N&timestamp=1712286766405&timestamp2=1b778c7486b1c1b341baeb5d665bfcdc&isRB=Y&imp=N&ptype=&isYesterday=N&f=1R
        let body = `p=FT_bet&${top.param}n&odd_f_type=${top.userData.odd_f_type}&golds=${data.amount}&gid=${data.gid}&gtype=FT&wtype=${data.wtype}&rtype=${data.wtype}${data.chose_team}&chose_team=${data.chose_team}&ioratio=${ioratio}&con=${con}&ratio=${ratio}&autoOdd=Y&timestamp=${Date.now()}&timestamp2=${timestamp2}&isRB=Y&imp=N&ptype=&isYesterday=N&f=1R`;
        let orderResp = await fetch(`${location.protocol}//${host}/transform.php?ver=${top.ver}`, {
            "headers": {
                "accept": "*/*",
                "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
                "cache-control": "no-cache",
                "content-type": "application/x-www-form-urlencoded",
                "pragma": "no-cache",
                "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"96\", \"Google Chrome\";v=\"96\"",
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "\"Windows\"",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-origin",
                "Cookie": document.cookie
            },
            "referrer": `${location.protocol}//${host}/`,
            "referrerPolicy": "strict-origin-when-cross-origin",
            "body": body,
            "method": "POST",
            "mode": "cors",
            "credentials": "include"
        }).catch(err => {
            console.info("下单发生错误：" + JSON.stringify(err))
        });
        let orderRespTxt = await orderResp.text();
        let orderRespJson = xml2json(orderRespTxt);
        if (orderRespJson.serverresponse.errormsg) {
            console.info("下单失败")
            if (!isTry) {
                setTimeout(() => {
                    order(data, true)
                }, 3000);
            }
        } else {
            console.info(JSON.stringify(orderRespJson))
        }
    } catch (err) {
        console.info("下单发生异常：" + err.message)

    }
}


function xml2json(xml) {
    return new XML.ObjTree().parseXML(xml);
}

eventsMap.set("order", order);

init();

function loopTodayWagers() {
    getTodayWagers()
    setTimeout(() => {
        loopTodayWagers()
    }, 1000 * 60 * 1);
}




// ========================================================================
//  XML.ObjTree -- XML source code from/to JavaScript object like E4X
// ========================================================================

if (typeof (XML) == 'undefined') XML = function () { };

//  constructor

XML.ObjTree = function () {
    return this;
};

//  class variables

XML.ObjTree.VERSION = "0.23";

//  object prototype

XML.ObjTree.prototype.xmlDecl = '<?xml version="1.0" encoding="UTF-8" ?>\n';
XML.ObjTree.prototype.attr_prefix = '-';

//  method: parseXML( xmlsource )

XML.ObjTree.prototype.parseXML = function (xml) {
    var root;
    if (window.DOMParser) {
        var xmldom = new DOMParser();
        //      xmldom.async = false;           // DOMParser is always sync-mode
        var dom = xmldom.parseFromString(xml, "application/xml");
        if (!dom) return;
        root = dom.documentElement;
    } else if (window.ActiveXObject) {
        xmldom = new ActiveXObject('Microsoft.XMLDOM');
        xmldom.async = false;
        xmldom.loadXML(xml);
        root = xmldom.documentElement;
    }
    if (!root) return;
    return this.parseDOM(root);
};

//  method: parseHTTP( url, options, callback )

XML.ObjTree.prototype.parseHTTP = function (url, options, callback) {
    var myopt = {};
    for (var key in options) {
        myopt[key] = options[key];                  // copy object
    }
    if (!myopt.method) {
        if (typeof (myopt.postBody) == "undefined" &&
            typeof (myopt.postbody) == "undefined" &&
            typeof (myopt.parameters) == "undefined") {
            myopt.method = "get";
        } else {
            myopt.method = "post";
        }
    }
    if (callback) {
        myopt.asynchronous = true;                  // async-mode
        var __this = this;
        var __func = callback;
        var __save = myopt.onComplete;
        myopt.onComplete = function (trans) {
            var tree;
            if (trans && trans.responseXML && trans.responseXML.documentElement) {
                tree = __this.parseDOM(trans.responseXML.documentElement);
            }
            __func(tree, trans);
            if (__save) __save(trans);
        };
    } else {
        myopt.asynchronous = false;                 // sync-mode
    }
    var trans;
    if (typeof (HTTP) != "undefined" && HTTP.Request) {
        myopt.uri = url;
        var req = new HTTP.Request(myopt);        // JSAN
        if (req) trans = req.transport;
    } else if (typeof (Ajax) != "undefined" && Ajax.Request) {
        var req = new Ajax.Request(url, myopt);   // ptorotype.js
        if (req) trans = req.transport;
    }
    if (callback) return trans;
    if (trans && trans.responseXML && trans.responseXML.documentElement) {
        return this.parseDOM(trans.responseXML.documentElement);
    }
}

//  method: parseDOM( documentroot )

XML.ObjTree.prototype.parseDOM = function (root) {
    if (!root) return;

    this.__force_array = {};
    if (this.force_array) {
        for (var i = 0; i < this.force_array.length; i++) {
            this.__force_array[this.force_array[i]] = 1;
        }
    }

    var json = this.parseElement(root);   // parse root node
    if (this.__force_array[root.nodeName]) {
        json = [json];
    }
    if (root.nodeType != 11) {            // DOCUMENT_FRAGMENT_NODE
        var tmp = {};
        tmp[root.nodeName] = json;          // root nodeName
        json = tmp;
    }
    return json;
};

//  method: parseElement( element )

XML.ObjTree.prototype.parseElement = function (elem) {
    //  COMMENT_NODE
    if (elem.nodeType == 7) {
        return;
    }

    //  TEXT_NODE CDATA_SECTION_NODE
    if (elem.nodeType == 3 || elem.nodeType == 4) {
        var bool = elem.nodeValue.match(/[^\x00-\x20]/);
        if (bool == null) return;     // ignore white spaces
        return elem.nodeValue;
    }

    var retval;
    var cnt = {};

    //  parse attributes
    if (elem.attributes && elem.attributes.length) {
        retval = {};
        for (var i = 0; i < elem.attributes.length; i++) {
            var key = elem.attributes[i].nodeName;
            if (typeof (key) != "string") continue;
            var val = elem.attributes[i].nodeValue;
            if (!val) continue;
            key = this.attr_prefix + key;
            if (typeof (cnt[key]) == "undefined") cnt[key] = 0;
            cnt[key]++;
            this.addNode(retval, key, cnt[key], val);
        }
    }

    //  parse child nodes (recursive)
    if (elem.childNodes && elem.childNodes.length) {
        var textonly = true;
        if (retval) textonly = false;        // some attributes exists
        for (var i = 0; i < elem.childNodes.length && textonly; i++) {
            var ntype = elem.childNodes[i].nodeType;
            if (ntype == 3 || ntype == 4) continue;
            textonly = false;
        }
        if (textonly) {
            if (!retval) retval = "";
            for (var i = 0; i < elem.childNodes.length; i++) {
                retval += elem.childNodes[i].nodeValue;
            }
        } else {
            if (!retval) retval = {};
            for (var i = 0; i < elem.childNodes.length; i++) {
                var key = elem.childNodes[i].nodeName;
                if (typeof (key) != "string") continue;
                var val = this.parseElement(elem.childNodes[i]);
                if (!val) continue;
                if (typeof (cnt[key]) == "undefined") cnt[key] = 0;
                cnt[key]++;
                this.addNode(retval, key, cnt[key], val);
            }
        }
    }
    return retval;
};

//  method: addNode( hash, key, count, value )

XML.ObjTree.prototype.addNode = function (hash, key, cnts, val) {
    if (this.__force_array[key]) {
        if (cnts == 1) hash[key] = [];
        hash[key][hash[key].length] = val;      // push
    } else if (cnts == 1) {                   // 1st sibling
        hash[key] = val;
    } else if (cnts == 2) {                   // 2nd sibling
        hash[key] = [hash[key], val];
    } else {                                    // 3rd sibling and more
        hash[key][hash[key].length] = val;
    }
};

//  method: writeXML( tree )

XML.ObjTree.prototype.writeXML = function (tree) {
    var xml = this.hash_to_xml(null, tree);
    return this.xmlDecl + xml;
};

//  method: hash_to_xml( tagName, tree )

XML.ObjTree.prototype.hash_to_xml = function (name, tree) {
    var elem = [];
    var attr = [];
    for (var key in tree) {
        if (!tree.hasOwnProperty(key)) continue;
        var val = tree[key];
        if (key.charAt(0) != this.attr_prefix) {
            if (typeof (val) == "undefined" || val == null) {
                elem[elem.length] = "<" + key + " />";
            } else if (typeof (val) == "object" && val.constructor == Array) {
                elem[elem.length] = this.array_to_xml(key, val);
            } else if (typeof (val) == "object") {
                elem[elem.length] = this.hash_to_xml(key, val);
            } else {
                elem[elem.length] = this.scalar_to_xml(key, val);
            }
        } else {
            attr[attr.length] = " " + (key.substring(1)) + '="' + (this.xml_escape(val)) + '"';
        }
    }
    var jattr = attr.join("");
    var jelem = elem.join("");
    if (typeof (name) == "undefined" || name == null) {
        // no tag
    } else if (elem.length > 0) {
        if (jelem.match(/\n/)) {
            jelem = "<" + name + jattr + ">\n" + jelem + "</" + name + ">\n";
        } else {
            jelem = "<" + name + jattr + ">" + jelem + "</" + name + ">\n";
        }
    } else {
        jelem = "<" + name + jattr + " />\n";
    }
    return jelem;
};

//  method: array_to_xml( tagName, array )

XML.ObjTree.prototype.array_to_xml = function (name, array) {
    var out = [];
    for (var i = 0; i < array.length; i++) {
        var val = array[i];
        if (typeof (val) == "undefined" || val == null) {
            out[out.length] = "<" + name + " />";
        } else if (typeof (val) == "object" && val.constructor == Array) {
            out[out.length] = this.array_to_xml(name, val);
        } else if (typeof (val) == "object") {
            out[out.length] = this.hash_to_xml(name, val);
        } else {
            out[out.length] = this.scalar_to_xml(name, val);
        }
    }
    return out.join("");
};

//  method: scalar_to_xml( tagName, text )

XML.ObjTree.prototype.scalar_to_xml = function (name, text) {
    if (name == "#text") {
        return this.xml_escape(text);
    } else {
        return "<" + name + ">" + this.xml_escape(text) + "</" + name + ">\n";
    }
};

//  method: xml_escape( text )

XML.ObjTree.prototype.xml_escape = function (text) {
    return (text + '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
};


